//
//  ALStatusPictureView.swift
//  Swift01
//
//  Created by Miaoyang on 16/4/15.
//  Copyright © 2016年 Miaoyang. All rights reserved.
//

import UIKit


import SDWebImage

private let ReuseIdentifier = "ReuseIdentifier"
/// collectionViewcell的间距
private let ALStatusPictureViewCellMargin: CGFloat = 4

/// cell的最大列数为3列,列数使用整数
private let ALStatusPictureViewMaxColumn = 3

// 计算cell的宽和高
private let ALStatusPictureViewItemWH = (UIScreen.mainScreen().bounds.width - 2 * ALStatusCellMargin - (CGFloat(ALStatusPictureViewMaxColumn) - 1) * ALStatusPictureViewCellMargin) / CGFloat(ALStatusPictureViewMaxColumn)


class ALStatusPictureView: UICollectionView {
    
   
    
    //配图数组
    var pictureURLs:[NSURL]? {
        didSet{
            // 当别人设置配图的url后,我们就来计算配图的高度
            let size = calcViewSize()
            // 自己来约束大小,当cell给pictureURLs之后计算出宽高,然后重行修改约束
            // 自己来约束大小,当cell给pictureURLs之后计算出宽高,然后重行修改约束
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            ALPrint("配图大小: \(size)")
            self.reloadData()

            
        }
               }
        /// 计算配图的宽高
       private func calcViewSize() -> CGSize {
        // 设置collectionView layout
        layout.itemSize = CGSize(width: ALStatusPictureViewItemWH, height: ALStatusPictureViewItemWH)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        // 判断图片的数量
        let count = pictureURLs?.count ?? 0
        
        // 没有图片
        if count == 0 {
        ALPrint("没有图片")
        return CGSizeZero
        }
        
        // 1.张图片
        if count == 1 {
            // 默认大小
            var size = CGSize(width: ALStatusPictureViewItemWH, height: ALStatusPictureViewItemWH)
            
        // 返回图片本来的大小,拿到图片或获取大小`
            let url = pictureURLs?.first!
            //缓存图片有可能拿到也可能拿不到
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url!.absoluteString) {
                // 点坐标:像素 / 2, 在 SDWebimage 3.7.3以后
                size = image.size
                size = CGSize(width: size.width * UIScreen.mainScreen().scale, height: size.height * UIScreen.mainScreen().scale)
                
            }
            //如果图片太小或太大,度处理一下`
            if size.width < 40 {
                size.width = 40
            }
            let screenWidth = UIScreen.mainScreen().bounds.width
            
            if size.width > screenWidth * 0.5 {
                size.width = screenWidth * 0.5
            }
            
            
            layout.itemSize = size

        return size
       
        }
        
        layout.minimumInteritemSpacing = ALStatusPictureViewCellMargin
        layout.minimumLineSpacing = ALStatusPictureViewCellMargin
        // 多张图片,列数不确定
        // 2张和4图片显示2列,其他都显示3列
        var column = ALStatusPictureViewMaxColumn
        if count == 2 || count == 4 {
        column = 2
        }
        
        // 服务器开发用得比较多,分页,保证列数是整数
        // 2 + 2 - 1 / 2 = 1
        // 3 + 3 - 1 / 3 = 1
        // 4 + 2 - 1 / 2 = 2
        // 5 + 3 - 1 / 3 = 2
        // 6 + 3 - 1 / 3 = 2
        // 7 + 3 - 1 / 3 = 3
        // 行数 = (总个数 + 列数 - 1) / 列数
        let row = (count + column - 1) / column
        
        // 计算宽度和高度
        // 宽度 = 列数 * item宽度 + (列数 - 1) * 列间距
        let widht = CGFloat(column) * ALStatusPictureViewItemWH + (CGFloat(column) - 1) * ALStatusPictureViewCellMargin
        
        // 高度度 = 行数 * item高度 + (行数 - 1) * 行间距
        let height = CGFloat(row) * ALStatusPictureViewItemWH + (CGFloat(row) - 1) * ALStatusPictureViewCellMargin
        return CGSize(width: widht, height: height)
        
        }
    
    
    private var layout = UICollectionViewFlowLayout()
    
     required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    init(){
       super.init(frame: CGRectZero, collectionViewLayout: layout)
         //TODO:测试背景图
        backgroundColor = UIColor.clearColor()
    //MARK:设置数据源方法
        self.dataSource = self
        //注册cell
        self.registerClass(ALStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
    }
    
}
//MARK:扩展实现数据源方法
extension ALStatusPictureView:UICollectionViewDataSource{
    //一个collectionView现实多少 个cell
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURLs?.count ?? 0
    }
    //每个cell显示数据的样式
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //从缓存池中获取,如果缓存池中没有,就会使用注册的cell
      let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! ALStatusPictureViewCell
//        cell.backgroundColor = UIColor.randomColor()
        //给每一个Cell设置图片
        cell.imageURL = pictureURLs![indexPath.item]
        return cell
    
    }
    
}
class ALStatusPictureViewCell: UICollectionViewCell {
    
    //每个cell需要一个图片的URL来下载图片,需要一个存储性构造函数来保存
    var imageURL:NSURL?{
        
        didSet{
            
            bkgImageView.sd_setImageWithURL(imageURL!)
        }
    }
     required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //设置UI
        preareUI()
    }
    private func preareUI(){
        
        bkgImageView.contentMode = UIViewContentMode.ScaleAspectFill
        bkgImageView.clipsToBounds = true
        
        //1.添加控件
        contentView.addSubview(bkgImageView)
        //2.添加约束
        bkgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        
    }
   
    //MAK:懒加载
    private lazy var bkgImageView:UIImageView = UIImageView()
}

